import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Form, Input, Select, Avatar, Button, Upload, Icon, message,Checkbox } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import api from "../../../api/api";
import axios from 'axios';
import lodash from 'lodash'
// import { Upload, message, Button, Icon } from 'antd';
const { Option } = Select;
const FormItem = Form.Item;


function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('请选择png或者jpg图片');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2M');
  }
  return isJpgOrPng && isLt2M;
}

@Form.create()
class Model extends React.Component {

  formRef = React.createRef()
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      hiddenFlag:true,
      visible: false,
      logoImageUrl: '',
      intervalObj: Object,
      intervalCount: 0,
      param: {
        id:"",
        areaId : "",
        roomName : "",
        roomType : "",
        roomPrice: undefined,
        status : undefined,
      }
    };
  }
  componentDidMount() {
    this.clearData()
    this.props.onRef(this)
  }
  componentWillUnmount(){
    clearInterval(this.state.intervalObj)
  }
//确定
  handleOk = () => {
    this.props.form.validateFields((error, values) => {
      console.log(values)
      if (error != null) {
        return;
      }else{
        const that = this;
          let {param} = this.state
        if (values.areaId=="天津和平区") {
          values.areaId=1
        }else if(values.areaId=="天津南开区"){
          values.areaId=2
        }

        param.areaId = values.areaId
        param.status=values.status
        param.roomName = values.roomName
        param.roomType = values.roomType
        param.roomPrice = values.roomPrice
            this.setState({param}, () => {
              this.personData()
            })
          }

    })
  }

  //添加，编辑请求提交
  personData() {
    let url = ""
    if(this.props.data.type === 2) {  //编辑
      url = api.api_URL + "/roommanager/updateRoomByRoomId"
      let { param } = this.state
      param.id = this.props.data.gridList.id
      this.setState({ param }, () => {
        this.addUser(url)
      })
    }else {                         //添加
      url = api.api_URL + "/roommanager/insertRoom"
      if(this.props.data.type === 1) {
        this.addUser(url)
      }
    }

  }


  //初始化编辑数据
  initEditData = () => {
    let that = this;
    that.setBaseInfo()
  }
  //编辑的初始值设置
  setBaseInfo(){
    let that = this;
    let data = this.props.data.gridList
    const { form } = this.props;
      Object.keys(form.getFieldsValue()).forEach(key => {
        const obj = {};
        if (data[key]) {
          obj[key] = data[key] || null;
        }
        form.setFieldsValue(obj);
      });

  }
  //编辑添加的请求
  addUser(url){
    const that = this;
    console.log(this.state.param)
    axios({
      method: 'POST',
      url: url,
      data: JSON.stringify(this.state.param),
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": "application/json;charset=UTF-8"
      },
    }).then(function (response) {
      that.handleCancel()
      message.success({content:"成功！"})

    }).catch(function (error) {
      message.error({content:"失败！"})
      console.log(error);
     })
  }
  handleCancel = e => {
    this.clearData()
    this.props.handleCancel()
  };
 //公司下拉框
  companySelect=[];
  getCompanySelect(){
    let that = this;
    let dataList = [];
    let url = api.api_URL+"/admin/company/queryAllCompanyInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
    axios.get(url, {
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": api.ContentType
      }
    }).then(function (res) {
      if (res.data.code != 1) {
        alert(res.data.msg);
        return;
      }
      let companyInfoList = res.data.data.companyInfoList;
      for (let i = 0; i < companyInfoList.length; i++) {
        let comData = companyInfoList[i];
        const data = {};
        data.key = comData.thirdCompanyId;
        data.label = comData.companyName;
        dataList[i] = data;
      }
      for (let i = 0; i < dataList.length; i++) {
        that.companySelect.push(<Option key={dataList[i].key} value={dataList[i].key}>{dataList[i].label}</Option>);
      }

    }).catch(function (err) {
      console.log(err);
    })
  }


  statusChange =(value)=> {
    let that=this;
        that.setState({
          param:{
            status:value
          }
        })

    }

  departmentChange=(value)=> {
    this.setState({
      selectDepartmentId: value
    })
    let {param} = this.state
    param.deptCode= value
    }


  //清空form表单数据
  clearData() {
    this.props.form.resetFields();
    this.setState({
      gname:"",
      deptName:"",
      cqName:"",
      logoImageUrl:"",
      hiddenFlag: true
    })
  }

  handleAvatarChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      console.log("handleAvatarChange===",info)
      this.setState({
        logoImageUrl: info.file.response.data.filename,
        loading: false,
      })
    }
  };

  render() {
    const { getFieldDecorator, getFieldError } = this.props.form
    const { logoImageUrl } = this.state;
    const CheckboxGroup = Checkbox.Group;
    const uploadButton = (
        <div>
          {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div className="ant-upload-text">上传头像</div>
        </div>
    );
    return (
      <div>
        <Modal
          title={this.props.data.title}
          visible={this.props.data.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form name="control-ref"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            layout="horizontal"
          >
            <FormItem  label="区域名称" name="areaId"  allowClear >
              {getFieldDecorator("areaId", {
                initialValue:"1",
              })(
                  <Select>
                    <Option key="1">天津和平区</Option>
                    <Option key="2">天津南开区</Option>
                  </Select>
              )}

            </FormItem>
            <FormItem  label="房间号" name="roomName" >
              {getFieldDecorator("roomName", {})(
                  <Input  placeholder="请输入房间号" />
              )}
            </FormItem>
            <FormItem label="房间类型"  name="roomType">
              {getFieldDecorator("roomType", {
                initialValue: "双人间"
              })(
                  <Select>
                    <Option key="单人间">单人间</Option>
                    <Option key="双人间">双人间</Option>
                  </Select>
              )}

            </FormItem>
            <FormItem   label="房间价格" name="roomPrice" >
              {getFieldDecorator("roomPrice", {
              rules: [{ required: true, message: '请填写价格!'}] ,
              })(
                  <Input placeholder="请输入房间价格" />
              )}
            </FormItem>
            <FormItem  label="选择状态" name="status">
              {getFieldDecorator("status", {
                initialValue: "0"
              })(
                  <Select onChange={this.statusChange} >
                    <Option key="0">未入住</Option>
                    <Option key="1">已入住</Option>
                    <Option key="2">已预定</Option>
                  </Select>
              )}
            </FormItem>

          </Form>
        </Modal>
      </div>
    );
  }
}
Model.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}
export default Model
